'use client';

import React, { useState, useEffect, useRef } from 'react';
import { ProLayout, MenuDataItem } from '@ant-design/pro-components';
import { 
  HomeOutlined,
  ExperimentOutlined, 
  ShoppingCartOutlined,
  UserOutlined, 
  TeamOutlined,
  LogoutOutlined,
  BellOutlined
} from '@ant-design/icons';
import { useRouter, usePathname } from 'next/navigation';
import { Dropdown, Space, Breadcrumb, Badge, List, Button, Typography, Empty, Spin } from 'antd';
import { useAuth } from './AuthProvider';
import { useMessage } from '../../hooks/useMessage';
import { notificationApi } from '@/apis/notification';
import { NotificationInfo } from '@/types/system';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

const { Text } = Typography;

const menuData: MenuDataItem[] = [

  {
    path: '/instruments',
    name: '仪器管理',
    icon: <ExperimentOutlined />,
  },
  {
    path: '/orders',
    name: '订单管理',
    icon: <ShoppingCartOutlined />,
  },
  {
    path: '/users',
    name: '用户管理',
    icon: <UserOutlined />,
  },
  {
    path: '/teams',
    name: '团队管理',
    icon: <TeamOutlined />,
  },
  {
    path: '/home-management',
    name: '首页管理',
    icon: <HomeOutlined />,
  },
];

interface AdminLayoutProps {
  children: React.ReactNode;
}

interface CachedRoute {
  content: React.ReactNode;
  timestamp: number;
}

const AdminLayout: React.FC<AdminLayoutProps> = ({ children }) => {
  const router = useRouter();
  const pathname = usePathname();
  const { userInfo, logout } = useAuth();
  const [collapsed, setCollapsed] = useState(false);
  const cachedRoutesRef = useRef<Map<string, CachedRoute>>(new Map());
  const [, forceUpdate] = useState({});
  const message = useMessage();

  // 通知相关状态
  const [notifications, setNotifications] = useState<NotificationInfo[]>([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [notificationLoading, setNotificationLoading] = useState(false);
  const [notificationOpen, setNotificationOpen] = useState(false);

  // 缓存当前路由的内容
  useEffect(() => {
    if (pathname && children) {
      const cache = cachedRoutesRef.current;
      cache.set(pathname, {
        content: children,
        timestamp: Date.now(),
      });
      
      // 限制缓存数量，最多保留10个页面
      if (cache.size > 10) {
        const entries = Array.from(cache.entries());
        entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
        const oldestKey = entries[0][0];
        cache.delete(oldestKey);
      }
      
      // 强制更新组件以反映缓存变化
      forceUpdate({});
    }
  }, [pathname, children]);

  const handleMenuClick = (path: string) => {
    router.push(path);
  };

  // 获取通知列表
  const fetchNotifications = async () => {
    setNotificationLoading(true);
    try {
      const response = await notificationApi.getNotifications({ 
        current: 1, 
        pageSize: 20 
      });
      if (response.success) {
        setNotifications(response.data.data);
        setUnreadCount(response.data.data.filter(n => !n.isRead).length);
      }
    } catch (error) {
      console.error('获取通知失败:', error);
    } finally {
      setNotificationLoading(false);
    }
  };

  // 标记单个通知为已读
  const markAsRead = async (id: string | number) => {
    try {
      await notificationApi.markAsRead(String(id));
      setNotifications(prev => 
        prev.map(n => n.id === id ? { ...n, isRead: true } : n)
      );
      setUnreadCount(prev => Math.max(0, prev - 1));
    } catch (error) {
      console.error('标记已读失败:', error);
    }
  };

  // 全部标记为已读
  const markAllAsRead = async () => {
    const unreadIds = notifications.filter(n => !n.isRead).map(n => String(n.id));
    if (unreadIds.length === 0) return;

    try {
      await notificationApi.batchMarkAsRead(unreadIds);
      setNotifications(prev => 
        prev.map(n => ({ ...n, isRead: true }))
      );
      setUnreadCount(0);
      message.success('已全部标记为已读');
    } catch (error) {
      console.error('批量标记已读失败:', error);
      message.error('操作失败');
    }
  };

  // 处理通知点击
  const handleNotificationClick = (notification: NotificationInfo) => {
    // 如果未读，先标记为已读
    if (!notification.isRead) {
      markAsRead(notification.id);
    }

    // 如果有目标链接，跳转到对应页面
    if (notification.targetUrl) {
      router.push(notification.targetUrl);
      setNotificationOpen(false);
    }
  };

  // 初始化获取通知
  useEffect(() => {
    fetchNotifications();
    
    // 定时刷新通知（每30秒）
    const interval = setInterval(fetchNotifications, 30000);
    return () => clearInterval(interval);
  }, []);

  // 通知下拉内容
  const notificationDropdownContent = (
    <div style={{ width: 380, maxHeight: 500, overflow: 'hidden' ,backgroundColor: '#fff'}}>
      <div style={{ 
        padding: '12px 16px', 
        borderBottom: '1px solid #f0f0f0',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <span style={{ fontWeight: 'bold' }}>通知消息</span>
        {unreadCount > 0 && (
          <Button 
            type="link" 
            size="small" 
            onClick={markAllAsRead}
            style={{ padding: 0 }}
          >
            全部已读
          </Button>
        )}
      </div>
      
      <div style={{ maxHeight: 400, overflowY: 'auto' }}>
        {notificationLoading ? (
          <div style={{ padding: '40px 0', textAlign: 'center' }}>
            <Spin />
          </div>
        ) : notifications.length === 0 ? (
          <Empty 
            description="暂无通知" 
            style={{ padding: '40px 0' }}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        ) : (
          <List
            dataSource={notifications}
            renderItem={(item) => (
              <List.Item
                style={{
                  padding: '12px 16px',
                  cursor: 'pointer',
                  backgroundColor: item.isRead ? 'transparent' : '#f6ffed',
                  borderLeft: item.isRead ? 'none' : '3px solid #52c41a'
                }}
                onClick={() => handleNotificationClick(item)}
              >
                <List.Item.Meta
                  title={
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                      <Text 
                        strong={!item.isRead}
                        style={{ 
                          fontSize: '14px',
                          lineHeight: '20px',
                          flex: 1,
                          marginRight: '8px'
                        }}
                        ellipsis={{ tooltip: item.title }}
                      >
                        {item.title}
                      </Text>
                      {!item.isRead && (
                        <div style={{
                          width: '8px',
                          height: '8px',
                          borderRadius: '50%',
                          backgroundColor: '#ff4d4f',
                          flexShrink: 0
                        }} />
                      )}
                    </div>
                  }
                  description={
                    <div>
                      <Text 
                        type="secondary" 
                        style={{ 
                          fontSize: '13px',
                          lineHeight: '18px',
                          display: 'block',
                          marginBottom: '4px'
                        }}
                        ellipsis={{ tooltip: item.content }}
                      >
                        {item.content}
                      </Text>
                      <Text 
                        type="secondary" 
                        style={{ fontSize: '12px' }}
                      >
                        {dayjs(item.createdAt).fromNow()}
                      </Text>
                    </div>
                  }
                />
              </List.Item>
            )}
          />
        )}
      </div>
    </div>
  );

  const handleLogout = () => {
    message.success('已退出登录');
    logout();
  };

  const userMenuItems = [
    {
      key: 'profile',
      label: '个人资料',
      icon: <UserOutlined />,
    },
    {
      key: 'settings',
      label: '账户设置',
    },
    {
      type: 'divider' as const,
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: handleLogout,
    },
  ];

  // 获取当前路由的缓存内容，如果没有则显示当前children
  const getCurrentContent = () => {
    const cache = cachedRoutesRef.current;
    const cachedRoute = cache.get(pathname);
    
    if (cachedRoute) {
      return cachedRoute.content;
    }
    
    return children;
  };

  // 生成面包屑
  const getBreadcrumbItems = () => {
    const breadcrumbItems: Array<{ title: string; href?: string }> = [
      {
        title: '首页',
        href: '/home-management',
      },
    ];

    // 根据当前路径添加面包屑项
    const currentMenu = menuData.find(menu => menu.path === pathname);
    if (currentMenu?.name) {
      breadcrumbItems.push({
        title: currentMenu.name,
      });
    }

    return breadcrumbItems;
  };

  return (
    <ProLayout
      title="预约管理系统"
      logo="/logo.svg"
      layout="mix"
      splitMenus={false}
      navTheme="light"
      fixedHeader
      fixSiderbar
      collapsed={collapsed}
      onCollapse={setCollapsed}
      menuDataRender={() => menuData}
      location={{
        pathname,
      }}
      menuItemRender={(item, dom) => (
        <div onClick={() => item.path && handleMenuClick(item.path)}>
          {dom}
        </div>
      )}
      avatarProps={{
        src: userInfo?.avatar || '/default-avatar.png',
        title: userInfo?.name || '用户',
        size: 'small',
        render: (props, dom) => (
          <Space size="large">
            {/* 通知铃铛 */}
            <Dropdown
              open={notificationOpen}
              onOpenChange={setNotificationOpen}
              popupRender={() => notificationDropdownContent}
              trigger={['click']}
              placement="bottomRight"
            >
              <Badge count={unreadCount} size="small" offset={[-5, 5]}>
                <BellOutlined 
                  style={{ 
                    fontSize: '18px', 
                    cursor: 'pointer',
                    color: unreadCount > 0 ? '#1890ff' : '#666'
                  }} 
                />
              </Badge>
            </Dropdown>

            {/* 用户菜单 */}
            <Dropdown
              menu={{
                items: userMenuItems,
              }}
              placement="bottomRight"
            >
              <Space style={{ cursor: 'pointer' }}>
                {dom}
              </Space>
            </Dropdown>
          </Space>
        ),
      }}
      headerContentRender={() => (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
          <Breadcrumb
            items={getBreadcrumbItems()}
          />
          <span style={{ color: '#666' }}>
            欢迎使用预约管理系统
          </span>
        </div>
      )}
      footerRender={() => (
        <div style={{ textAlign: 'center', color: '#999' }}>
          预约管理系统 ©2024 Created by Your Company
        </div>
      )}
      onMenuHeaderClick={() => router.push('/home-management')}
      menuProps={{
        selectedKeys: [pathname],
      }}
    >
      <div style={{ minHeight: 'calc(100vh - 112px)' }}>
        {getCurrentContent()}
      </div>
    </ProLayout>
  );
};

export default AdminLayout; 